﻿using ProtoBuf.Message;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using AutoChess;

namespace AutoChess
{
    /// <summary>
    /// 玩家的逻辑运行实体. 
    ///     逻辑实体的数据的变换 应该是由逻辑操作指令运算后进行变更. 
    ///     不能直接取玩家缓存数据.缓存数据是实时同步的服务器数据 . 用于刷新数据
    /// </summary> 
    class PlayerEntity
    {
        public long playerGuid;
       
        public readonly List<ACHero> HeroUnits = new List<ACHero>();
        public bool IsSelfPlayer { get { return playerGuid == StaticData.playerData.playerId; } }

        private ShipUnit shipUnit = null;
        public ShipUnit ShipUnit
        {
            get { return shipUnit; }
        }

        public PlayerEntity() { }
        public PlayerEntity(long playerGuid) {
            this.playerGuid = playerGuid;
        }

        /// <summary> 筛选相同棋子 </summary>
        private Dictionary<int, List<ACHero>> tempChessCache = new Dictionary<int, List<ACHero>>();
        /// <summary> 筛选相同英雄 </summary>
        private Dictionary<int, List<ACHero>> tempHeroIdCache = new Dictionary<int, List<ACHero>>();

        /// <summary>
        /// 获取指定站位上的格子的棋子Id
        /// </summary>
        /// <param name="index">1-12 的战场位置</param>
        /// <returns></returns>
        public int GetChessIdByFightGridIndex(int index)
        {
            var temp = index - 1;
            foreach (var item in HeroUnits)
            {
                if ((item.MapGrid.GridType == GridType.FightGrid|| item.MapGrid.GridType == GridType.EnemyGrid)&&
                    item.MapGrid.LocalIndex == temp)
                {
                    return item.ChessID;
                }
            }
            return -1;
        }

        /// <summary>
        /// 上升星Buff
        /// </summary>
        /// <param name="star">要升星的棋子</param>
        public void OnUpStarBuff(List<AutoChessChessInfo> star)
        {
            if (star != null)
            {
                foreach (var hero in star)
                {
                   var heroUnit =  GetHeroUnitByServerIndex(hero.pos);
                    if (heroUnit != null)
                    {
                        heroUnit.OnUpStarBuff(hero);
                    }
                    else
                    {
                        Debug.LogError("升星buff 数据异常!");
                    }
                }
            }
        }
        
        /// <summary>
        /// 下升星Buff
        /// </summary>
        /// <param name="star">要复原的棋子</param>
        public void OffUpStarBuff(List<AutoChessChessInfo> star)
        {
            foreach (var hero in star) //阵容正常的棋子
            {
                var heroUnit = GetHeroUnitByServerIndex(hero.pos);
                if (heroUnit != null)
                {
                    heroUnit.OffUpStarBuff(hero);
                }
                else
                {
                    Debug.LogError("升星buff 数据异常!");
                }
            }
        }
        public ACHero GetHeroUnitByServerIndex(int serverIndex)
        {
            foreach (var item in HeroUnits)
            {
                if (item.MapGrid.GridType == GridType.FightGrid)
                {
                    if (item.MapGrid.ServerIndex == serverIndex)
                        return item;
                }
                else if (item.MapGrid.GridType == GridType.EnemyGrid)
                {
                    if (item.MapGrid.EnemyServerIndex == serverIndex)
                        return item;
                }
            }
            return null;
        }

        /// <summary>
        /// 刷新可以升星的英雄特效或者 升星UI
        /// </summary>
        public void RefreshHeroNumberState()
        {
            if (!IsSelfPlayer)//只有自己显示升星什么的
                return;
            tempChessCache.Clear();
            tempHeroIdCache.Clear();

            for (int i = 0; i <HeroUnits.Count; i++)
            {
                var chessId = HeroUnits[i].ChessID;
                var heroId = HeroUnits[i].HeroID;
               
                //默认全部关闭升星UI , 不显示英雄多个 或升星特效
                HeroUnits[i].SetShowStar(false);
                HeroUnits[i].SetFieldHeroEffectType(HeroEffectType.None);

                //筛选相同棋子
                if (tempChessCache.ContainsKey(chessId))
                {
                    tempChessCache[chessId].Add(HeroUnits[i]);
                }
                else
                {
                    tempChessCache[chessId] = new List<ACHero>() { HeroUnits[i] };
                }

                //筛选相同英雄
                if (tempHeroIdCache.ContainsKey(heroId))
                {
                    tempHeroIdCache[heroId].Add(HeroUnits[i]);
                }
                else
                {
                    tempHeroIdCache[heroId] = new List<ACHero>() { HeroUnits[i] };
                }
            }

            //遍历棋子 看是否有相同类型的英雄
            foreach (var item in tempHeroIdCache)
            {
                if (item.Value.Count >= 2)//场上有2个以上的相同的HeroID
                {
                    bool ifFightHave = false;
                    foreach (var hero in item.Value)
                    {
                        if (hero.MapGrid.GridType == GridType.FightGrid || hero.MapGrid.GridType == GridType.PreChooseGrid)
                        {
                            ifFightHave = true;
                        }
                    }
                    if (ifFightHave == true)
                    {
                        foreach (var hero in item.Value)
                        {
                            hero.SetFieldHeroEffectType(HeroEffectType.Field2Hero);
                        }
                    }
                }
            }

            //遍历棋子 看是否有升星UI 显示和 升星特效
            foreach (var item in tempChessCache)
            {
                if (item.Value.Count >= 3)
                {
                    List<ACHero> onField = new List<ACHero>();
                    foreach (var hero in item.Value)
                    {
                        //筛选升星按钮 个数算战场和被选区的
                        if (AutoChessManager.Ins.GetCurrentStateType() == AutoChessModeState.ShowFightState)
                        {
                            if (hero.MapGrid.GridType != GridType.ShopGrid && hero.MapGrid.GridType != GridType.FightGrid)
                            {
                                onField.Add(hero);
                            }
                        }
                        else
                        {
                            if (hero.MapGrid.GridType != GridType.ShopGrid)
                            {
                                onField.Add(hero);
                            }
                        }
                        //筛选升星特效 整个战场3个以上显示特效
                        hero.SetFieldHeroEffectType(HeroEffectType.Field3Chess);
                    }

                    //战场和被选区中有3个以上相同的棋子 但是只有被选区显示升星显示升星按钮
                    if (onField.Count >= 3)
                    {
                        for (int i = 0; i < onField.Count; i++)
                        {
                            if (onField[i].MapGrid.GridType == GridType.PreChooseGrid)
                            {
                                onField[i].SetShowStar(true);
                            }
                        }
                    }
                }
            }

            // 统一刷新渲染
            for (int i = 0; i < HeroUnits.Count; i++)
            {
                HeroUnits[i].RefrehRenderer();
            }
        }

        public void AddHeroUnit(ACHero heroUnit)
        {
            HeroUnits.Add(heroUnit);
        }

        /// <summary>
        /// 移除一个实体
        /// </summary>
        public void RemoveHeroUnit(ACHero unit)
        {
           // unit.OnDestroy();
            ActorManager.Instance.DestroyActor(unit);
            HeroUnits.Remove(unit);
        }
        /// <summary>
        /// 添加一条船
        /// </summary>
        public void AddShip(ShipUnit shipUnit)
        {
            this.shipUnit = shipUnit;
        }
      
        public void FightGridHeroDestroy()
        {
            for (int i = HeroUnits.Count - 1; i >= 0; i--)
            {
                if (HeroUnits[i].MapGrid.GridType == GridType.FightGrid)
                {
                    HeroUnits[i].LeaveBattleField();
                }
            }
        }
        public void GridHeroDisconnectRenderer(GridType gridType)
        {
            for (int i = HeroUnits.Count - 1; i >= 0; i--)
            {
                if (HeroUnits[i].MapGrid.GridType == gridType)
                {
                    HeroUnits[i].DisconnectRenderer();
                }
            }
        }
        public void GridHeroReconnectRenderer(GridType gridType)
        {
            for (int i = HeroUnits.Count - 1; i >= 0; i--)
            {
                if (HeroUnits[i].MapGrid.GridType == gridType)
                {
                    HeroUnits[i].ConnectRenderer( AutoChessFieldViewCtr.Ins.GetHeroUnitRenderer());
                }
            }
        }
        /// <summary>
        /// 这个英雄离开战场
        /// </summary>
        public void ClearAllHero()
        {
            playerGuid = 0;
            for (int i = HeroUnits.Count - 1; i >= 0; i--)
            {
                HeroUnits[i].LeaveBattleField();
            }
            HeroUnits.Clear();
            if (shipUnit != null)
            {
                //销毁船
                shipUnit.DisconnectRenderer();
                shipUnit = null;
            }
        }

        /// <summary>
        /// 这个英雄离开战场
        /// </summary>
        public void LeaveBattleField(bool delateShip = true)
        {
            playerGuid = 0;
            for (int i = HeroUnits.Count-1; i >= 0; i--)
            {
                HeroUnits[i].LeaveBattleField();
            }
            HeroUnits.Clear();
            if (delateShip&& shipUnit!=null)
            {
                //销毁船
                shipUnit.DisconnectRenderer();
            }
        }

        public void ShowAllEnemy()
        {
            foreach (var hero in HeroUnits)
            {
                if (hero.MapGrid.GridType == GridType.EnemyGrid)
                {
                    hero.Relife();
                    hero.heroUnitRenderer.PlayEnterFieldEffect();
                }
            }
        }
        public void HideAllEnemy()
        {
            foreach (var hero in HeroUnits)
            {
                if (hero.MapGrid.GridType == GridType.EnemyGrid)
                {
                    hero.isDeathHide = true;
                    hero.HeroDeath();
                }
            }
        }

        #region 战斗表现相关接口
        /// <summary>
        /// 战斗玩家入场
        /// </summary>
        public void HerosEnterCenter(bool isEnemy = false)
        {
            var gridType = isEnemy ? GridType.EnemyGrid : GridType.FightGrid;
            foreach (var hero in HeroUnits)
            {
                if (hero.MapGrid.GridType == gridType)
                {
                    var centerIndex = hero.MapGrid.ColumnIndex; //获取对应的在的 中心格子位置
                    var centerGrid = AutoChessMapMgr.Ins.GetGridPos(GridType.CenterGrid, centerIndex);
                    hero.JumpToPosition(centerGrid.Position, JumpType.Forward, ()=> {
                        hero.isDeathHide = true;
                        hero.HeroDeath();
                    }); //跳到指定点  后直接隐藏 写死
                }
            }
        }
        /// <summary>
        /// 战场返回
        /// </summary>
        public void HerosReturnBack(bool isEnemy = false)
        {
            var gridType = isEnemy ? GridType.EnemyGrid : GridType.FightGrid;
            foreach (var hero in HeroUnits)
            {
                if (hero.MapGrid.GridType == gridType)
                {
                    var pos = hero.MapGrid.Position;
                    hero.JumpToPosition(pos, JumpType.Back, null); //跳到指定点
                }
            }
        }

        public void HeroRelife()
        {
            foreach (var hero in HeroUnits)
            {
                hero.Relife();
            }
        }
        /// <summary>
        /// 战斗死亡
        /// </summary>
        /// <param name="leftHeros">剩余的人</param>
        public void HeroDeath(List<ProtoBuf.Message.AutoChessChessInfo> leftHeros,bool isEnemy = false)
        {
            List<ACHero> allFightHero = new List<ACHero>();
           
            foreach (var hero in HeroUnits)
            {
                if (hero.MapGrid.GridType == GridType.FightGrid || hero.MapGrid.GridType == GridType.EnemyGrid)
                {
                    hero.isDeathHide = true;
                    allFightHero.Add(hero);
                 }
            }

            for (int i = allFightHero.Count-1; i >=0 ; i--)
            {
                foreach (var item in leftHeros)
                {
                    //敌人的就一定是战场上的
                    var serverIndex = isEnemy ? allFightHero[i].MapGrid.EnemyServerIndex : allFightHero[i].MapGrid.ServerIndex;
                    if (serverIndex == item.pos)
                    {
                        allFightHero[i].isDeathHide = false;//没有死亡
                    }
                }
            }

            foreach (var item in allFightHero)
            {
                item.HeroDeath();
            }
        }
       
        private ACHero GetHeroUnit(int chessId, GridType type, int gridIndex)
        {
            foreach (var hero in HeroUnits)
            {
                if (hero.ChessID == chessId && hero.MapGrid.EqualsGrid(gridIndex, type))
                {
                    return hero;
                }
            }
            return null;
        }
        #endregion
    }
}